package com.gane.maple.service.impl;

import com.gane.maple.dao.UserDAO;
import com.gane.maple.entity.User;
import com.gane.maple.jdbc.routing.ClientDataSource;
import com.gane.maple.jdbc.routing.annotation.DataSourceRouting;
import com.gane.maple.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Description UserServiceImpl
 * @Date 2020/4/24 7:41
 * @Created by 王弘博
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDAO userDAO;

    /**
     * 把 @DataSourceRouting 放进 dao 层
     *
     * @param userId
     * @return
     */
    @Override
    public User selectByUserId(String userId) {
        User userFromMaster = userDAO.selectByUserId(userId);
        System.out.println("查询master库：" + userFromMaster);
        return userFromMaster;
    }

    /**
     * 把 @DataSourceRouting 放进 dao 层
     *
     * @param userName
     * @return
     */
    @Override
    public User selectByUserName(String userName) {
        User userFromSlave = userDAO.selectByUserName(userName);
        System.out.println("查询slave库：" + userFromSlave);
        return userFromSlave;
    }

    /**
     * 把 @DataSourceRouting 放进 dao 层
     * 观察进入aspect几次
     *
     * @param userId
     * @param userName
     * @return
     */
    @Override
    public User selectFromMasterAndSlave(String userId, String userName) {

        User userFromMaster = userDAO.selectByUserId(userId);
        System.out.println("查询master库：" + userFromMaster);

        User userFromSlave = userDAO.selectByUserName(userName);
        System.out.println("查询slave库：" + userFromSlave);

        return userFromMaster;
    }

    /**
     * 把 @DataSourceRouting 放进 service 层 和 dao 层。判断具体以哪个datasource为准
     *
     * @param userId
     * @param userName
     * @return
     */
    @DataSourceRouting(value = ClientDataSource.SLAVE)
    @Override
    public User selectFromMasterAndSlaveWithDataSourceRoutingInDao(String userId, String userName) {

        User userFromMaster = userDAO.selectByUserId(userId);
        System.out.println("查询master库：" + userFromMaster);

        User userFromSlave = userDAO.selectByUserName(userName);
        System.out.println("查询slave库：" + userFromSlave);

        return userFromMaster;
    }

    @DataSourceRouting(value = ClientDataSource.SLAVE)
    @Override
    public User selectFromMasterAndSlaveWithoutDataSourceRoutingInDao(String userId, String userName) {

        User userFromMaster = userDAO.selectByUserIdWithoutDataSourceRouting(userId);
        System.out.println("查询master库：" + userFromMaster);

        User userFromSlave = userDAO.selectByUserNameWithoutDataSourceRouting(userName);
        System.out.println("查询slave库：" + userFromSlave);

        return userFromMaster;
    }


}
